package com.zhang.es;

import com.google.gson.Gson;
import com.zhang.model.User;
import org.apache.lucene.search.TermQuery;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.Before;
import org.junit.Test;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.Map;

import static org.elasticsearch.index.query.QueryBuilders.queryStringQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;

/**
 * @program: elasitcsearch
 * @description:
 * @author: Dawson.Zhang
 * @create: 2020-03-09
 **/
public class fuxiday1 {
    private TransportClient client;
    @Before
    public void init() throws Exception{
        //1:创建一个setting，主要用于配置，设置连接集群地址
        Settings settings = Settings.builder()
            .put("cluster.name", "my-elasticsearch")
            .build();
        //创建一个Pbtc对象:9200
        client = new PreBuiltTransportClient(settings)
            .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.117.128"), 9301))
            .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.117.128"),9302));

    }

    @Test
    public void createIndex() throws Exception{
        // 创建一个索引库
        client.admin().indices().prepareCreate("索引名").get();
        //4:关闭Client
        client.close();
    }
    @Test
    public void putMapping() throws  Exception{
        XContentBuilder builder = XContentFactory.jsonBuilder();
        builder.startObject()
                    .startObject("user")
                        .startObject("properties")
                            .startObject("id")
                                .field("type","long")
                                .field("index",true)
                                .field("store",true)
                            .endObject()
                            .startObject("userName")
                                .field("type","text")
                                .field("index",true)
                                .field("store",true)
                                .field("analyzer","ik_smart")
                            .endObject()
                        .endObject()
                    .endObject()
                .endObject();
        client.admin().indices().preparePutMapping("java1").setType("user").setSource(builder).get();
        client.close();
    }
    @Test
    public void delMap(){
        //删除指定索引库
        client.admin().indices().prepareDelete("索引库名").get();
        client.close();
    }
    @Test
    public void addDoc(){
        for (int i = 1; i < 80; i++) {
            User user = new User();
            user.setId(i);
            user.setUserName("保家卫国"+i+"");
            Gson gson = new Gson();
            String s = gson.toJson(user);
            client.prepareIndex("java1", "user", ""+i+"")
                .setSource(s)
                .get();
        }
        client.close();
    }
    @Test
    public void updateDoc(){
        Gson gson = new Gson();
        String s = gson.toJson(new User(1, "按当时发生的发生的发生大幅阿斯顿"));
        client.prepareUpdate("java1","user","14")
            .setDoc(s)
            .get();
        client.close();
    }
    @Test
    public void delDoc(){
        client.prepareDelete("java1","user","14").get();
        client.close();
    }

    public void search(QueryBuilder queryBuilder){
        HighlightBuilder highlightBuilder = new HighlightBuilder().field("userName").preTags("<span>").postTags("</span>");

        SearchResponse searchResponse = client.prepareSearch("java1").setTypes("user").setQuery(queryBuilder).highlighter(highlightBuilder).get();
        SearchHits hits = searchResponse.getHits();
        System.out.println("一共查询到"+hits.getTotalHits()+"条数据");
        SearchHit[] hits1 = hits.getHits();
        hits.forEach(
            hit->{
                Map<String, Object> source = hit.getSource();
                Object userName = source.get("userName");
                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                HighlightField userName1 = highlightFields.get("userName");
                Text[] fragments = userName1.fragments();
            }
        );
        client.close();
    }

    @Test
    public void selectById(){
        QueryBuilder builder = QueryBuilders.idsQuery().addIds("12","15");
        search(builder);
    }
    @Test
    public void getByTerm(){
        QueryBuilder builder = QueryBuilders.boolQuery().must(termQuery("userName","1"));
        search(builder);
    }
    @Test
    public void getByQueryString(){
        QueryBuilder builder = QueryBuilders.boolQuery().must(queryStringQuery("保家卫国").defaultField("userName"));
        search(builder);
    }
}
